package form;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import toolkit.CollectionUtils;

abstract public class FormNode
{
	protected HashMap<String, Object> attributes = new HashMap<String, Object>();
	
	public void setAttribute(String name, Object value)
	{
		attributes.put(name, value);
	}
	
	public Object getAttribute(String name)
	{
		return attributes.get(name);
	}
	
	public void removeAttribute(String name)
	{
		attributes.remove(name);
	}
	
	public void setAttributes(Map<String, Object> attributes)
	{
		this.attributes = new HashMap<String, Object>(attributes);
	}
	
	public Map<String, Object> getAttributes()
	{
		return attributes;
	}
	
	public void removeAttributes()
	{
		this.attributes.clear();
	}
	
	protected String getAttributesCode()
	{
		String code = "";
		
		for (String name: attributes.keySet())
		{
			code += (' ' + name + "=\"" + attributes.get(name) + '"');
		}
		
		return code;
	}
	
	public void addClassName(String className)
	{
		HashSet<String> classNames = getClassNames();
		
		classNames.add(className);
		
		setClassNames(classNames);
	}
	
	public void removeClassName(String className)
	{
		HashSet<String> classNames = getClassNames();
		
		classNames.remove(className);
		
		setClassNames(classNames);
	}
	
	public void setClassNames(HashSet<String> classNames)
	{
		setAttribute("class", CollectionUtils.join(classNames, " "));
	}
	
	public HashSet<String> getClassNames()
	{
		String classNames = (String) getAttribute("class");
		
		if (classNames == null)
		{
			return new HashSet<String>();
		}
		
		return new HashSet<String>(Arrays.asList(classNames.split(" ")));
	}
	
	abstract public boolean isShortTag();
	
	abstract public String getTagName();
	
	abstract public String getCode();
	
	@Override
	public String toString()
	{
		return getCode();
	}
}
